<template>
  <div class="app-container">
    <el-card>
      <el-button type="primary" icon="el-icon-plus" @click="dialogVisible=true">添加角色</el-button>
      <el-dialog
        title="角色信息"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="dialogVisible"
        :show-close="false"
        top="7vh"
        width="50%"
        @close="refresh"
      >
        <el-form ref="role" :model="roleForm" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName" />
          </el-form-item>
          <el-form-item label="状态" prop="defunct">
            <el-switch v-model="roleForm.defunct" />
          </el-form-item>
          <el-form-item label="菜单权限">
            <el-tree
              v-if="dialogVisible"
              ref="menuTree"
              class="tree-border"
              :data="resourceOptions"
              show-checkbox
              node-key="id"
              :default-checked-keys="defaultCheckedKeys"
              empty-text="加载中，请稍后"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="insertRole">保存</el-button>
        </span>
      </el-dialog>
    </el-card>
    <el-card style="margin-top: 1rem">
      <el-table :data="roles" stripe>
        <el-table-column prop="roleId" label="角色编号" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="defunct" label="状态">
          <template slot-scope="scope">
            <el-link :type="scope.row.defunct==='N'?'success':'danger'" @click="updateDefunct(scope.row)">
              {{ scope.row.defunct === 'N' ? 'Available' : 'Reserved' }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-link icon="el-icon-edit" type="primary" @click="editRole(scope.row.roleId)">修改</el-link>
            <el-link
              icon="el-icon-delete"
              style="margin-left: 0.5rem"
              type="danger"
              @click="deleteRole(scope.row.roleId)"
            >删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px;"
        background
        :current-page="currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>

import { deleteRole, insertRole, listResource, listRole, roleById, updateDefunct } from '@/api/user'

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      roleId: -1,
      dialogVisible: false,
      roles: [{ roleId: 0, roleName: 'admin', defunct: 'N' }],
      defaultCheckedKeys: [],
      roleForm: {
        roleName: '',
        defunct: false
      },
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      resourceOptions: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1'
        }]
      }]
    }
  },
  created() {
    this.listRole()
    this.listResource()
  },
  methods: {
    insertRole() {
      this.$refs.role.validate(valid => {
        if (valid) {
          if (this.$refs.menuTree.getCheckedKeys().length < 1) {
            this.$message.info('请分配角色权限')
            return
          }
          const form = new FormData()
          form.set('roleName', this.roleForm.roleName)
          form.set('defunct', this.roleForm.defunct ? 'Y' : 'N')
          form.set('roleId', String(this.roleId || -1))
          form.set('resourceIds', this.$refs.menuTree.getCheckedKeys().toString())
          insertRole(form).then(res => {
            this.$message.success(res.message)
            this.dialogVisible = false
            this.listRole()
          })
        }
      })
    },
    updateDefunct(row) {
      const form = new FormData()
      form.set('roleId', row.roleId)
      form.set('defunct', row.defunct)
      updateDefunct(form).then(res => {
        this.$message.success(res.message)
        row.defunct = row.defunct === 'N' ? 'Y' : 'N'
      })
    },
    deleteRole(roleId) {
      this.$confirm('此操作将永久删除角色数据，是否继续删除？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        deleteRole({ roleId: roleId }).then(res => {
          this.$message.success(res.message)
          this.listRole()
        })
      })
    },
    editRole(roleId) {
      roleById({ roleId: roleId }).then(res => {
        this.roleId = roleId
        this.roleForm.roleName = res.data.roleName || ''
        this.roleForm.defunct = res.data.defunct === 'Y'
        this.defaultCheckedKeys = res.data.resourceIds
        this.dialogVisible = true
      })
    },
    listRole() {
      listRole({ current: this.currentPage, size: this.pageSize }).then(res => {
        this.totalNum = Number(res.data.total)
        this.roles = res.data.records
      })
    },
    listResource() {
      listResource().then(res => {
        this.resourceOptions = res.data
      })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.listRole()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.listRole()
    },
    refresh() {
      this.roleForm.roleName = ''
      this.roleForm.defunct = false
      this.defaultCheckedKeys = []
      this.listRole()
    }
  }
}
</script>

<style scoped>
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
}
</style>
